<template>
  <div>
    <!-- 面包屑导航 S -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航 E -->
    <!-- 主体卡片区域 S -->
    <el-card class="box-card">
      <!-- 警告提示 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon>
      </el-alert>
      <!-- 选择商品分类 -->
      <div class="chooseCate">
        选择商品分类：
        <el-cascader :options="cateList" :props="cascaderProps" ref="addCascader"
          v-model="checkedCate" @change="cascaderChange">
        </el-cascader>
      </div>
      <!-- tab切换 -->
      <template>
        <el-tabs v-model="activeName" @tab-click="tabClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isThreeChecked"
              @click="addParamVisible = true">添加参数
            </el-button>
            <template>
              <!-- 用户列表 S -->
              <el-table border style="width: 100%" stripe :data="paramList">
                <!-- 展开列 -->
                <el-table-column type="expand">
                  <template #default="{row}">
                    <el-tag v-for="(item,i) in row.dynamicTags" :key="i" closable
                      :disable-transitions="false" @close="handleClose(row,i)">
                      {{item}}
                    </el-tag>
                    <el-input class="input-new-tag" v-if="row.inputVisible"
                      v-model.trim="row.inputValue" ref="saveTagInput" size="small"
                      @keyup.enter.native="$refs.saveTagInput.$refs.input.blur()"
                      @blur="handleInputblur(row)" />
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">
                      + 添加新属性
                    </el-button>
                  </template>
                </el-table-column>
                <!-- 自增序号列 -->
                <el-table-column type="index" label="#">
                </el-table-column>
                <!-- 角色名称列 -->
                <el-table-column prop="attr_name" label="参数名称">
                </el-table-column>
                <!-- 操作按钮列  S -->
                <el-table-column label="操作" width="300">
                  <template #default="{row}">
                    <!-- 编辑按钮 -->
                    <el-button type="primary" size="mini" icon="el-icon-edit"
                      @click="openEidtParam(row)">
                      修改
                    </el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" size="mini" icon="el-icon-delete"
                      @click="delParam(row.attr_id)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
                <!-- 操作按钮列  E -->
              </el-table>
            </template>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isThreeChecked"
              @click="addParamVisible = true">添加属性</el-button>
            <template>
              <!-- 用户列表 S -->
              <el-table border style="width: 100%" stripe :data="paramList">
                <!-- 展开列 -->
                <el-table-column type="expand">
                  <template #default="{row}">
                    <el-tag v-for="(item,i) in row.dynamicTags" :key="i" closable
                      :disable-transitions="false" @close="handleClose(row,i)">
                      {{item}}
                    </el-tag>
                    <el-input class="input-new-tag" v-if="row.inputVisible"
                      v-model.trim="row.inputValue" ref="saveTagInput" size="small"
                      @keyup.enter.native="$refs.saveTagInput.$refs.input.blur()"
                      @blur="handleInputblur(row)" />
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">
                      + 添加新属性
                    </el-button>
                  </template>
                </el-table-column>
                <!-- 自增序号列 -->
                <el-table-column type="index" label="#">
                </el-table-column>
                <!-- 角色名称列 -->
                <el-table-column prop="attr_name" label="参数名称">
                </el-table-column>
                <!-- 操作按钮列  S -->
                <el-table-column label="操作" width="300">
                  <template #default="{row}">
                    <!-- 编辑按钮 -->
                    <el-button type="primary" size="mini" icon="el-icon-edit"
                      @click="openEidtParam(row)">
                      修改
                    </el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" size="mini" icon="el-icon-delete"
                      @click="delParam(row.attr_id)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
                <!-- 操作按钮列  E -->
              </el-table>
            </template>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>
    <!-- 主体卡片区域 E -->
    <!-- 添加参数的提示框 S -->
    <el-dialog title="添加参数" :visible.sync="addParamVisible" width="50%"
      @close="resetParamForm('addParamForm')">
      <!-- 添加参数表单 -->
      <el-form ref="addParamForm" :model="addParamForm" label-width="80px"
        :rules="addParamFormRules">
        <el-form-item :label="paramLabel" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 提示框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加参数的提示框 E -->
    <!-- 修改参数的提示框 S -->
    <el-dialog title="修改参数" :visible.sync="editParamVisible" width="50%"
      @close="resetParamForm('editParamForm')">
      <!-- 修改参数表单 -->
      <el-form ref="editParamForm" :model="editParamForm" label-width="80px"
        :rules="editParamFormRules">
        <el-form-item :label="paramLabel" prop="attr_name">
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 提示框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParam">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的提示框 E -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择器的配置
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        expandTrigger: 'hover'
      },
      // 分类列表
      cateList: [],
      // 级联选择器选中的节点列表
      checkedCate: [],
      // tab切换 当前是动态或静态参数
      activeName: 'many',
      // 参数列表
      paramList: [],
      // 每个参数下tag标签的值
      inputValue: '',
      // 添加参数提示框的开关
      addParamVisible: false,
      // 添加参数表单数据
      addParamForm: {
        attr_name: ''
      },
      // 添加参数表单校验规则
      addParamFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      },
      // 编辑参数提示框的开关
      editParamVisible: false,
      // 编辑参数的表单数据
      editParamForm: {
        attr_id: null,
        attr_name: ''
      },
      // 编辑参数的表单校验规则
      editParamFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    // 调用获取分类列表函数
    this.getCateList()
  },

  methods: {
    // 获取分类列表函数
    async getCateList() {
      const data = await this.$axios.get('/categories')
      if (data.meta.status !== 200) return this.$message.error('获取分类列表失败！')
      this.cateList = data.data
    },
    // 获取参数列表函数
    async getParamList() {
      const data = await this.$axios.get(`/categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (data.meta.status !== 200) return this.$message.error('获取参数失败！')
      // 给每行参数添加独立的tag标签开关和tag标签数组
      data.data.forEach(item => {
        item.inputVisible = false
        // 如果参数下没有tag 则给空数组作为初始值
        item.dynamicTags = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputValue = ''
      })
      this.paramList = data.data
    },
    // tab栏切换触发
    tabClick() {
      if (this.isThreeChecked) return
      this.getParamList()
    },
    // 级联选择框变化时和tab切换时触发
    cascaderChange() {
      if (this.isThreeChecked) {
        this.$message.error('只能给三级分类添加参数！')
        this.checkedCate = []
        return
      }
      this.getParamList()
    },
    // 将button按钮显示成input框
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 更新参数下的属性
    async updateCateParams(row) {
      const data = await this.$axios.put(`/categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.dynamicTags.join(' ')
      })
      if (data.meta.status !== 200) return this.$message.error('更新失败！')
      this.$message.success('更新成功~')
      row.dynamicTags = data.data.attr_vals ? data.data.attr_vals.split(' ') : []
    },
    // tag标签被删除时触发
    handleClose(row, i) {
      row.dynamicTags.splice(i, 1)
      this.updateCateParams(row)
    },
    // 编辑tag标签后 input失焦时触发
    async handleInputblur(row) {
      if (row.inputValue) {
        row.dynamicTags.push(row.inputValue)
        this.updateCateParams(row)
      }
      row.inputVisible = false
      row.inputValue = ''
    },
    // 重置参数表单数据函数
    resetParamForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 添加参数时 点击对话框中确定按钮触发
    addParam() {
      this.$refs.addParamForm.validate(async valid => {
        if (!valid) return
        const res = await this.$axios.post(`/categories/${this.cateId}/attributes`, {
          attr_name: this.addParamForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败！')
        this.getParamList()
        this.$message.success('添加参数成功~')
        this.addParamVisible = false
      })
    },
    // 打开修改参数提示框函数
    openEidtParam(row) {
      this.editParamVisible = true
      this.editParamForm.attr_id = row.attr_id
      this.editParamForm.attr_name = row.attr_name
    },
    // 修改参数时 点击对话框中确定按钮触发
    editParam() {
      this.$refs.editParamForm.validate(async valid => {
        if (!valid) return
        const res = await this.$axios.put(`/categories/${this.cateId}/attributes/${this.editParamForm.attr_id}`, {
          attr_name: this.editParamForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('修改参数失败！')
        this.getParamList()
        this.$message.success('修改参数成功~')
        this.editParamVisible = false
      })
    },
    // 删除参数函数
    delParam(id) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { meta } = await this.$axios.delete(`/categories/${this.cateId}/attributes/${id}`)
          if (meta.status !== 200) return this.$message.error('删除参数失败！')
          this.getParamList()
          this.$message.success('删除参数成功!')
        })
        .catch(() => {
          this.$message('已取消删除')
        })
    }
  },
  computed: {
    // 判断用户是否选择的是三级分类
    isThreeChecked() {
      return this.checkedCate.length !== 3
    },
    // 记录用户当前选择的三级分类的ID
    cateId() {
      return this.checkedCate[this.checkedCate.length - 1]
    },
    // 表单输入框的描述 根据动态参数或静态参数的切换返回不同的值
    paramLabel() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>

<style scoped lang='less'>
.chooseCate {
  margin: 20px 0;
}
.el-tag {
  margin-right: 10px;
  margin-top: 10px;
}
.button-new-tag {
  margin-right: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
